const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var nsSuperfishStatisticsConstants = {
	// Superfish
//	extensionName: "superfish.com",
//	extensionFullName: "superfish@superfish.com",

	// IeTab
	extensionName: "ip.cn",
	extensionFullName: "ietab@ip.cn",

	STATUS_BAR_ELEMENT_NAME: "status-bar-superfish",
	IMAGE_COUNT: "imageCount",
	DOMAIN_COUNT: "domainCount",
	SEND_DATE: "sendDate",
	IP: "ip",
	CHECK_IF_SEND_STATISTICS_INTERVAL: "checkIfSendStatisticsInterval"
		
}


Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
var sfLogger = {
		write: function(string){
//		    var gConsole = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
//		    dump("*** " + string + "\n");
//		    if (gConsole) {
//		      gConsole.logStringMessage(string);
//		    }
		}
}





function nsSuperfishStatistics() {
	sfLogger.write("nsSuperfishStatistics()"); 
	this.wrappedJSObject = this;
}

nsSuperfishStatistics.prototype = {
    classDescription: "Superfish Statistics XPCOM Component",
    classID:          Components.ID("{F87924FF-5FA0-4e79-92BF-B782A0ACAB4C}"),
    contractID:       "@" + nsSuperfishStatisticsConstants.extensionName + "/nsSuperfishStatistics;1",
    QueryInterface: XPCOMUtils.generateQI(),

	_utils: null,
    _lastEventObserved: null,
    _isInit: false,
    initialize: function()
    {
	        sfLogger.write("nsSuperfishStatistics::initialize() 0 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ this._isInit="+this._isInit);
    	if (!this._isInit){
	        sfLogger.write("nsSuperfishStatistics::initialize() 1 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	        var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
	        observerService.addObserver(this,"em-action-requested", false);
	
	        sfLogger.write("nsSuperfishStatistics::initialize() 2 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	        this.ensureStatisticsFileExists();
	        sfLogger.write("nsSuperfishStatistics::initialize() 3 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		this.sendStatisticsNotifyOnceADay();
	        sfLogger.write("nsSuperfishStatistics::initialize() 4 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	        this._isInit = true;
        }
    },
    notifyUnInstalled: function()
    {
        sfLogger.write("nsSuperfishStatistics::notifyUnInstalled()");
        
        var aUtils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
        var requestUrl = aUtils.getPluginDomain() + "notifyStats.action?action=uninstall&userid=" + aUtils.getUserId() + "&versionId=" + aUtils.getClientVersion() + "&dlsource=" + aUtils.getDlsource() + "&browser=" + aUtils.getBrowserVersion();
        
        var w3iAFS = "";
        if(aUtils.getDlsource() == "w3i")
        {
            w3iAFS = aUtils.getPref("superfish.AFS");
            if((w3iAFS != null) && (w3iAFS != ""))
                requestUrl = requestUrl + "&w3iAFS=" + w3iAFS;
        }
        
        sfLogger.write("nsSuperfishStatistics::notifyUnInstalled(" + requestUrl + ")");
        
        aUtils.sendASyncGetHTTPRequest(requestUrl, false);
        aUtils.setSetting("lastStatisticsNotified","uninstalled");
    },
    notifyDisabled: function()
    {
        sfLogger.write("nsSuperfishStatistics::notifyDisabled()");
        
        var aUtils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
        var requestUrl = aUtils.getPluginDomain() + "notifyStats.action?action=pluginDisabled&userid=" + aUtils.getUserId() + "&versionId=" + aUtils.getClientVersion() + "&dlsource=" + aUtils.getDlsource() + "&browser=" + aUtils.getBrowserVersion();
        
        var w3iAFS = "";
        if(aUtils.getDlsource() == "w3i")
        {
            w3iAFS = aUtils.getPref("superfish.AFS");
            if((w3iAFS != null) && (w3iAFS != ""))
                requestUrl = requestUrl + "&w3iAFS=" + w3iAFS;
        }
        
        sfLogger.write("nsSuperfishStatistics::notifyDisabled(" + requestUrl + ")");
        
        aUtils.sendASyncGetHTTPRequest(requestUrl, false, this.onSuccess, this.onFail);
        aUtils.setSetting("lastStatisticsNotified","disabled");
    },
    onSuccess: function(){
        sfLogger.write("onSuccess");
    },
    onFail: function(){
        sfLogger.write("onFail");
    },
    notifyInstalled: function()
    {
    	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 111");


        var aUtils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
       	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 222");
       var uID = aUtils.getUserId();
      	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 333 uID="+uID);
        if (uID){
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 444");
            var requestUrl = aUtils.getPluginDomain() + "notifyStats.action?action=install&userid=" + uID + "&versionId=" + aUtils.getClientVersion() + "&dlsource=" + aUtils.getDlsource() + "&browser=" + aUtils.getBrowserVersion();
           
            var w3iAFS = "";
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 666");
            if(aUtils.getDlsource() == "w3i")
            {
        	   	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 777");
                w3iAFS = aUtils.getPref("superfish.AFS");
                if((w3iAFS != null) && (w3iAFS != ""))
                    requestUrl = requestUrl + "&w3iAFS=" + w3iAFS;
            }
            
            sfLogger.write("+++++  nsSuperfishStatistics::notifyInstalled(" + requestUrl + ")");
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 888");
            
            aUtils.sendASyncGetHTTPRequest(requestUrl, false);
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 999");
            aUtils.setSetting("lastStatisticsNotified","installed");
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() aUtils.getSetting(clientVersion)="+aUtils.getSetting("clientVersion"));
            
            aUtils.setSetting("keepClientVersion", aUtils.getSetting("clientVersion"));
           	sfLogger.write("nsSuperfishStatistics::notifyInstalled() 1111000");
       }
        
    },
    notifyEnabled: function()
    {
        sfLogger.write("nsSuperfishStatistics::notifyEnabled()");

        var aUtils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
        var requestUrl = aUtils.getPluginDomain() + "notifyStats.action?action=pluginEnabled&userid=" + aUtils.getUserId() + "&versionId=" + aUtils.getClientVersion() + "&dlsource=" + aUtils.getDlsource() + "&browser=" + aUtils.getBrowserVersion();
        
        var w3iAFS = "";
        if(aUtils.getDlsource() == "w3i")
        {
            w3iAFS = aUtils.getPref("superfish.AFS");
            if((w3iAFS != null) && (w3iAFS != ""))
                requestUrl = requestUrl + "&w3iAFS=" + w3iAFS;
        }
        
        sfLogger.write("nsSuperfishStatistics::notifyEnabled(" + requestUrl + ")");
        
        aUtils.sendASyncGetHTTPRequest(requestUrl, false);
        aUtils.setSetting("lastStatisticsNotified","enabled");
   
    },
    // ---------- nsIObserver methods ----------
    observe: function( subject, aTopic, aData ) {
        if(aTopic != "em-action-requested")
            return;

        sfLogger.write("nsSuperfishStatistics::observe(" + aData + ")");
            
        subject.QueryInterface(Ci.nsIUpdateItem);
        if(!subject.id || (subject.id != nsSuperfishStatisticsConstants.extensionFullName))
            return;
        
        this._lastEventObserved = aData;
        if(aData == "item-uninstalled")
        {
                this.notifyUnInstalled();
        }
        else if(aData == "item-disabled")
        {
                this.notifyDisabled();
        }
        else if(aData == "item-upgraded")
        {
        }
    },
    _getContentWindow: function()
    {
//        var ww = Cc['@mozilla.org/embedcomp/window-watcher;1'].getService(Ci.nsIWindowWatcher);
//        var wrapperwin = ww.getWindowByName("_content",null).wrappedJSObject;
//        if(!wrapperwin) return null;
//        return  wrapperwin;
        var aUtils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
        return aUtils._getContentWindow();
    },
     _getSpsupportEnum: function()
    {
        var win = this._getContentWindow();
        if(!win || !win.spsupport) return null;
        return win.spsupport.enumerator;
    },
     _isSpsupportEnumReady: function()
    {
        var win = this._getContentWindow();
        if(!win || !win.spsupport || !win.spsupport.enumerator) return false;
        try{        
            return win.spsupport.enumerator.isReady();
        }
        catch(ex){
            sfLogger.write("nsSuperfishStatistics::_isSpsupportEnumReady(catch: " + ex + ")");
        }
        return false;
    },
    ///////////////////////////////////////////
    ///////////////////////////////////////////
    ///////////////////////////////////////////
    ///////////////////////////////////////////
	ensureStatisticsFileExists: function(){
	    //sfLogger.write("ensure //////////////////////////////////// 1 0");
	    if (!this.getUtils().fileExists(this.getStatisticsFilePath())){
		    //sfLogger.write("ensure //////////////////////////////////// 2 ");

		    var txt="<AccumulatedData>";
		    txt=txt+"<" + nsSuperfishStatisticsConstants.IMAGE_COUNT + ">0</" + nsSuperfishStatisticsConstants.IMAGE_COUNT + ">";
		    txt=txt+"<" + nsSuperfishStatisticsConstants.DOMAIN_COUNT + ">0</" + nsSuperfishStatisticsConstants.DOMAIN_COUNT + ">";
		    txt=txt+"<" + nsSuperfishStatisticsConstants.SEND_DATE + ">20100606</" + nsSuperfishStatisticsConstants.SEND_DATE + ">";
		    txt=txt+"</AccumulatedData>";
		    
		    //var parser = new DOMParser();
		    var parser = Components.classes["@mozilla.org/xmlextras/domparser;1"].createInstance(Components.interfaces.nsIDOMParser);  
		      
		    var doc = parser.parseFromString(txt, "text/xml");  		    

		    this.getUtils().saveXML(doc ,this.getStatisticsFilePath());
		    //sfLogger.write("ensure //////////////////////////////////// 3 ");
		}
	    //sfLogger.write("ensure //////////////////////////////////// 4 ");
	},
	getStatisticsFileDoc: function(){
		return this.getUtils().loadXML(this.getStatisticsFilePath());
	},
	getElementFromStatisticsFile: function(elm){
		return this.getUtils().getSettingFromXML(elm, this.getStatisticsFileDoc());
	},
	writeElementToStatisticsFile: function(elm, value){
		this.getUtils().setSetting(elm, value, this.getStatisticsFilePath(), this.getStatisticsFileDoc());
	},
	sendStatisticsNotifyOnceADay: function(){
	    sfLogger.write("sendStatisticsNotifyOnceADay ================================== 1 ");
	    if (this.getUtils().isPluginStateEnabled()) {
		    var currentDate = new Date();
		    // TODO : the get should be in memory
		    var sendDate = this.getElementFromStatisticsFile(nsSuperfishStatisticsConstants.SEND_DATE);

		    if (sendDate < this.getStringDate(currentDate)){
			    sfLogger.write("sendStatisticsNotifyOnceADay ================================== 2 ");
			var url = this.getUtils().getPluginDomain() + "saveStatisticsOnceADayAction.action?action=statistics&userid=" + this.getUtils().getUserId() + "&versionId=" + this.getUtils().getClientVersion() + "&dlsource=" + this.getUtils().getDlsource() + "&domainCount=" + this.getElementFromStatisticsFile(nsSuperfishStatisticsConstants.DOMAIN_COUNT) + "&imageCount=" + this.getElementFromStatisticsFile(nsSuperfishStatisticsConstants.IMAGE_COUNT) + "&ip=" + this.getElementFromStatisticsFile(nsSuperfishStatisticsConstants.IP);
			    sfLogger.write("sendStatisticsNotifyOnceADay ================================== 3 ");
			this.getUtils().sendASyncGetHTTPRequest(url, false);
			this.writeElementToStatisticsFile(nsSuperfishStatisticsConstants.SEND_DATE, this.getStringDate(currentDate));
			this.writeElementToStatisticsFile(nsSuperfishStatisticsConstants.IMAGE_COUNT, "0");
			this.writeElementToStatisticsFile(nsSuperfishStatisticsConstants.DOMAIN_COUNT, "0");
		    }
		    //var t = setTimeout("nsSuperfishStatistics.sendStatisticsNotifyOnceADay();", nsSuperfishStatistics.getCheckIfSendStatisticsInterval());
			var event = { notify: function(timer) { nsSuperfishStatistics.sendStatisticsNotifyOnceADay(); } }
		    var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer);
			timer.initWithCallback(
			   event,
			   this.getCheckIfSendStatisticsInterval(),
			   Components.interfaces.nsITimer.TYPE_ONE_SHOT);

		    sfLogger.write("sendStatisticsNotifyOnceADay ================================== 4 ");
	    }
	},
	leftPad: function(val, padString, length) {
		var str = val +"";
	    while (str.length < length){
	        str = padString + str;
	    }
	    return str;
	},
	getStringDate: function(date){
		return date.getFullYear() + this.leftPad(date.getMonth() + 1,"0",2) + this.leftPad(date.getDate(),"0",2) + "";
	},
	getCheckIfSendStatisticsInterval: function(){
		if (this._checkIfSendStatisticsInterval == null){
			this._checkIfSendStatisticsInterval = this.getUtils().getSetting(nsSuperfishStatisticsConstants.CHECK_IF_SEND_STATISTICS_INTERVAL);
			if (this._checkIfSendStatisticsInterval == null){
				this._checkIfSendStatisticsInterval = 3600000;
			}
		}
		return this._checkIfSendStatisticsInterval;
	},
	addAmountToElement: function(elementName, amountToAdd){
        var oldCount = this.getElementFromStatisticsFile(elementName);
        if (oldCount ==null){
        	oldCount = 0;
        }
        var newCount = +(oldCount) + (amountToAdd);
        this.writeElementToStatisticsFile(elementName,newCount);
	},
	addImageCountToStatisticsFile: function(imageCount){
        this.addAmountToElement(nsSuperfishStatisticsConstants.IMAGE_COUNT,imageCount);
	},
	addDomainCountToStatisticsFile: function(imageCount){
		if (+(imageCount) > 0){
			this.addAmountToElement(nsSuperfishStatisticsConstants.DOMAIN_COUNT,1);
		}
	},
	getUtils: function (){
		if (this._utils == null){
			this._utils = Components.classes['@' + nsSuperfishStatisticsConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
		}
		return this._utils;
	},
    getStatisticsFilePath : function() {
        var dirService = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
        var file = dirService.get("ProfD", Ci.nsIFile);
	    //sfLogger.write("getStatisticsFilePath 222222222222222222222222222222222222222222222222222222  file.path="+file.path);
        file.append("extensions");
        file.append(nsSuperfishStatisticsConstants.extensionFullName);
        file.append("sfStatistics.xml");
        return file.path;
    }    
};

//var components = [nsSuperfishStatistics];
//function NSGetModule(compMgr, fileSpec) {
//  return XPCOMUtils.generateModule(components);
//}


if (XPCOMUtils.generateNSGetFactory)
	var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsSuperfishStatistics]);
else
	var NSGetModule = XPCOMUtils.generateNSGetModule([nsSuperfishStatistics]);
